import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xianyu_school/utils/url.dart';
import 'dart:convert';
import '../registe/registePage.dart';
import '../entity/user/user.dart';

var url = urls().url;//访问url

class loginPage extends StatefulWidget {
  @override
  _loginPageState createState() => _loginPageState();
}

class _loginPageState extends State<loginPage> {
  final _formKey = new GlobalKey<FormState>();
  String _userID;
  String _password;
  bool _isChecked = true;
  IconData _checkIcon = Icons.check_box;

  void _onLogin() {
    final form = _formKey.currentState;
    form.save();
    if (_userID == '') {
      _showMessageDialog('账号不可为空');
      return;
    }
    if (_password == '') {
      _showMessageDialog('密码不可为空');
      return;
    }
    user user1 = new user();
    user1.username = _userID;
    user1.password = _password;
    String json1 = json.encode(user1);
    void postHttp() async {
      try {
        //print(json1);
        Response response = await Dio().post(url + "/users/login",data: json1);
        if(response.toString() == "success"){
          SharedPreferences prefs = await SharedPreferences.getInstance();
          prefs.setString("username", user1.username);
          Navigator.pop(context,user1.username);
        }
        else _showMessageDialog("用户名密码错误");
      }
      catch (e) {
        return ;
      }
    }
    postHttp();
  }

  void _showMessageDialog(String message) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: Text('提示'),
          content: Text(message),
          actions: <Widget>[
            FlatButton(
              child: Text("ok"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Widget _showEmailInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 7.5, 0.0, 0.0),
      child: TextFormField(
        maxLines: 1,
        keyboardType: TextInputType.emailAddress,
        autofocus: false,
        style: TextStyle(fontSize: 15),
        decoration: InputDecoration(
            border: InputBorder.none,
            hintText: '请输入帐号',
            icon: Icon(
              Icons.email,
              color: Colors.grey,
            )),
        onSaved: (value) => _userID = value.trim(),
      ),
    );
  }

  Widget _showPasswordInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        style: TextStyle(fontSize: 15),
        decoration: InputDecoration(
            border: InputBorder.none,
            hintText: '请输入密码',
            icon: new Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => _password = value.trim(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CupertinoNavigationBar(
          backgroundColor: Colors.yellow,
          middle: const Text('登录'),
        ),
        body: ListView(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.only(top: 30),
              height: 100,
            ),
            Form(
              key: _formKey,
              child: Container(
                height: 122,
                padding: const EdgeInsets.fromLTRB(25, 0, 25, 0),
                child: Card(
                  child: Column(
                    children: <Widget>[
                      _showEmailInput(),
                      Divider(
                        height: 0.5,
                        indent: 16.0,
                        color: Colors.grey[300],
                      ),
                      _showPasswordInput(),
                    ],
                  ),
                ),
              ),
            ),
            Container(
              height: 70,
              padding: const EdgeInsets.fromLTRB(35, 30, 35, 0),
              child: Row(
                children: [
                  OutlineButton(
                    child: Text('登录'),
                    textColor: Colors.orange,
                    color: Colors.white,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                    borderSide: BorderSide(color: Colors.orange, width: 1),
                    onPressed: () {
                      _onLogin();
                    },
                  ),
                  Expanded(
                    child: Text(''), // 中间用Expanded控件
                  ),
                  OutlineButton(
                    child: Text('注册'),
                    textColor: Colors.orange,
                    color: Colors.white,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                    borderSide: BorderSide(color: Colors.orange, width: 1),
                    onPressed: () {
                      Navigator.push(context, MaterialPageRoute(builder: (_) {
                        return registePage();
                      }));
                    },
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(40, 10, 50, 0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  IconButton(
                      icon: Icon(_checkIcon),
                      color: Colors.orange,
                      onPressed: () {
                        setState(() {
                          _isChecked = !_isChecked;
                          if (_isChecked) {
                            _checkIcon = Icons.check_box;
                          } else {
                            _checkIcon = Icons.check_box_outline_blank;
                          }
                        });
                      }),
                  Expanded(
                    child: RichText(
                        text: TextSpan(text: '我已经详细阅读并同意', style: TextStyle(color: Colors.black, fontSize: 13), children: <TextSpan>[
                          TextSpan(text: '《隐私政策》', style: TextStyle(color: Colors.blue, decoration: TextDecoration.underline)),
                          TextSpan(text: '和'),
                          TextSpan(text: '《用户协议》', style: TextStyle(color: Colors.blue, decoration: TextDecoration.underline))
                        ])),
                  )
                ],
              ),
            )
          ],
        )
    );
  }
}